package com.bbjob.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.bbjob.client.MsgBody;
import com.bbjob.client.SocketUser;
import com.bbjob.client.dataentity.ResultForDeliveryVersionUpgrade;
import com.bbjob.client.result.ResultForDeliverySysOrganization;
import com.bbjob.dto.Result;
import com.bbjob.mapper.DeliverySocketMsgLogMapper;
import com.bbjob.mapper.DeliverySysOrganizationMapper;
import com.bbjob.mapper.DeliveryUserMapper;
import com.bbjob.mapper.DeliveryVersionUpgradeMapper;
import com.bbjob.model.CenterMacSignin;
import com.bbjob.model.DeliverySocketMsgLog;
import com.bbjob.model.DeliverySysOrganization;
import com.bbjob.model.DeliveryUser;
import com.bbjob.model.DeliveryVersionUpgrade;
import com.bbjob.model.SysDictionary;
import com.bbjob.model.SysOrganization;
import com.bbjob.model.User;
import com.bbjob.query.MachineInfo;
import com.bbjob.service.ISystemService;
import com.bbjob.toolutil.DataEntity;
import com.bbjob.toolutil.HttpClientUtil;
import com.bbjob.toolutil.ListUtils;
import com.bbjob.util.Tool;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

@Service
public class SystemServiceImpl implements ISystemService {

	@Value("${sys.uniquecode}")
	private String uniquecode;
	@Value("${examol.center.url}")
	private String centerUrl;
	@Value("${examol.center.registe}")
	private String centerRegiste;
	@Value("${examol.center.validate}")
	private String centerValidate;
	@Value("${examol.center.testConn}")
	private String testUrl;
	@Value("${examol.center.organUrl}")
	private String organUrl;
	@Value("${examol.center.sys.dics.url}")
	private String centerSysDicsUrl;
	@Value("${examol.center.operation.auth.url}")
	private String centerOperationAuthUrl;
	@Value("${examol.center.difficulty.url}")
	private String centerDifficultyUrl;
	@Value("${examol.center.sys.changePwd.url}")
	private String centerChangePwdUrl;
	@Value("${examol.center.sys.organInfo.url}")
	private String centerSysOrganInfoUrl;
	@Value("${examol.center.sys.versionInfo.url}")
	private String centerSysVersionInfo;
	@Value("${oss.accessKeyId}")
	private String accessKeyId;
	@Value("${oss.accessKeySecret}")
	private String accessKeySecret;
	@Value("${oss.endpoint}")
	private String endpoint;
	@Value("${oss.bucket}")
	private String bucket;
	@Value("${sys.local.client.path}")
	private String clientPath;
	@Value("${examol.create.saveTeacher.url}")
	private String centerCreateUserUrl;
	@Value("${examol.create.editTeacher.url}")
	private String centerEditUserUrl;
	@Value("${examol.create.listTeacher.url}")
	private String centerListUserUrl;
	@Value("${examol.create.delTeacher.url}")
	private String centerDelUserUrl;
	@Resource
	private ServerSocketLine serverSocketLine;
	@Resource
	private ClientServiceImpl clientServiceImpl;
	@Resource
	private DeliverySocketMsgLogMapper deliverySocketMsgLogMapper;
	@Resource
	private DeliveryUserMapper deliveryUserMapper;
	@Resource
	private DeliverySysOrganizationMapper deliverySysOrganizationMapper;
	@Resource
	private DeliveryVersionUpgradeMapper deliveryVersionUpgradeMapper;
	@Resource
	private ISystemService systemService;

	@Override
	public Result registe(CenterMacSignin centerMacSignin,
			HttpServletRequest request) {

		if (StringUtils.isBlank(centerMacSignin.getMacAddress())) {

			String mac = getMac(request);
			if (StringUtils.isBlank(mac)) {
				return new Result(8001, "MAC地址不能为空");
			} else {
				centerMacSignin.setMacAddress(mac);
			}
		}

		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("macAddress", centerMacSignin.getMacAddress());
			params.put("uniqueCode", uniquecode);

			String resultStr = HttpClientUtil.doPost(centerUrl + centerRegiste,
					params);

			if (null != resultStr) {
				Result result = new Gson().fromJson(resultStr, Result.class);

				return result;
			} else {

				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public String getMac(HttpServletRequest request) {

		String ip = getAddrIp(request);
		String mac = "";
		try {
			mac = getMacAddress(ip);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return mac.toUpperCase();
	}

	private String getMacAddress(String ip) throws Exception {
		String result = command("ping " + ip + " -n 2");
		if (result.contains("TTL")) {
			result = command("arp -a " + ip);
		}
		String regExp = "([0-9A-Fa-f]{2})([-:][0-9A-Fa-f]{2}){5}";
		Pattern pattern = Pattern.compile(regExp);
		Matcher matcher = pattern.matcher(result);
		StringBuilder mac = new StringBuilder();
		while (matcher.find()) {
			String temp = matcher.group();
			mac.append(temp);
		}
		return mac.toString();
	}

	private String command(String cmd) throws Exception {
		Process process = Runtime.getRuntime().exec(cmd);
		process.waitFor();
		InputStream in = process.getInputStream();
		StringBuilder result = new StringBuilder();
		byte[] data = new byte[256];
		while (in.read(data) != -1) {
			String encoding = System.getProperty("sun.jnu.encoding");
			result.append(new String(data, encoding));
		}
		return result.toString();
	}

	private String getAddrIp(HttpServletRequest request) {
		String ipString = request.getHeader("x-forwarded-for");
		if (StringUtils.isBlank(ipString)
				|| "unknown".equalsIgnoreCase(ipString)) {
			ipString = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ipString)
				|| "unknown".equalsIgnoreCase(ipString)) {
			ipString = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ipString)
				|| "unknown".equalsIgnoreCase(ipString)) {
			ipString = request.getRemoteAddr();
		}

		// 多个路由时，取第一个非unknown的ip
		final String[] arr = ipString.split(",");
		for (final String str : arr) {
			if (!"unknown".equalsIgnoreCase(str)) {
				ipString = str;
				break;
			}
		}

		return ipString;
	}

	@Override
	public Result TestConn() {
		try {
			String resultStr = HttpClientUtil.doGetWithMinSeconds(centerUrl
					+ testUrl);

			if (null != resultStr && !"".equals(resultStr)) {
				Result result = new Gson().fromJson(resultStr, Result.class);

				return result;
			} else {

				return new Result(8106, "连接异常");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(8106, "连接异常");
		}
	}

	@Override
	public Result getOrgansByPid(SysOrganization organ) {

		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("id", organ.getId());
			params.put("uniqueCode", uniquecode);

			String resultStr = HttpClientUtil.doPost(centerUrl + organUrl,
					params);

			Result result = new Gson().fromJson(resultStr, Result.class);

			return result;
		} catch (Exception e) {
			e.printStackTrace();

			return null;
		}
	}

	public List<MachineInfo> setMachineInfo() {
		List<MachineInfo> list = new ArrayList<MachineInfo>();
		boolean flag = false;
		int count = 0;
		Runtime r = Runtime.getRuntime();
		Process p;
		try {
			p = r.exec("arp -a");
			BufferedReader br = new BufferedReader(new InputStreamReader(
					p.getInputStream(), "gbk"));
			String inline;
			while ((inline = br.readLine()) != null) {
				if (inline.indexOf("接口") > -1) {
					flag = !flag;
					if (!flag) {
						// 碰到下一个"接口"退出循环
						break;
					}
				}
				if (flag) {
					count++;
					if (count > 2) {
						// 有效IP
						String[] str = inline.split(" {4}");
						MachineInfo info = new MachineInfo();
						info.setIp(str[0].trim());
						info.setStatus(0);
						list.add(info);
					}
				}
				System.out.println(inline);
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// setHostNameByIp(list);

		return list;
	}

	private void setHostNameByIp(List<MachineInfo> list) {

		for (MachineInfo info : list) {
			String command = "ping -a " + info.getIp();
			Runtime r = Runtime.getRuntime();
			Process p;
			try {
				p = r.exec(command);
				BufferedReader br = new BufferedReader(new InputStreamReader(
						p.getInputStream()));
				String inline;
				while ((inline = br.readLine()) != null) {
					if (inline.indexOf("[") > -1) {
						int start = inline.indexOf("Ping ");
						int end = inline.indexOf("[");
						String hostname = inline.substring(
								start + "Ping ".length(), end - 1);
						System.out.println(hostname);
						info.setCname(hostname);
					}
				}
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public List<MachineInfo> getMachineStatus(Integer examId) {
		Map<String, MachineInfo> infoMap = clientServiceImpl
				.getMachineInfoMap();

		Map<String, SocketUser> map = serverSocketLine.getClients();
		List<String> ips = new ArrayList<String>(map.keySet());

		List<String> infoIps = new ArrayList<String>(infoMap.keySet());

		List<MachineInfo> list = new ArrayList<MachineInfo>();

		for (String ip : infoIps) {
			MachineInfo machineInfo = infoMap.get(ip);
			if (examId == machineInfo.getField4()) {
				if (map.get(machineInfo.getIp()) == null) {
					machineInfo.setStatus(0);
					list.add(machineInfo);
				} else {
					if (ips.contains(machineInfo.getIp())) {
						machineInfo.setCname(map.get(machineInfo.getIp())
								.getSocket().getInetAddress().getHostName());
						machineInfo.setStatus(1);
					} else {
						machineInfo.setStatus(0);
					}

					list.add(machineInfo);
				}

			}

			/*
			 * if (map.get(machineInfo.getIp()) == null && examId ==
			 * machineInfo.getField4()) { list.add(machineInfo); } else { if
			 * (ips.contains(machineInfo.getIp()) && examId ==
			 * machineInfo.getField4()) {
			 * machineInfo.setCname(map.get(machineInfo
			 * .getIp()).getSocket().getInetAddress().getHostName());
			 * machineInfo.setStatus(1); list.add(machineInfo); } }
			 */

		}

		/*
		 * List<MachineInfo> machines = setMachineInfo(); Map<String,
		 * SocketUser> map = serverSocketLine.getClients();
		 * 
		 * List<String> ips = new ArrayList<String>(map.keySet());
		 * 
		 * Map<Integer, ArrayList<MachineInfo>> returnMap = new HashMap<Integer,
		 * ArrayList<MachineInfo>>();
		 * 
		 * for (MachineInfo info : machines) { if (ips.contains(info.getIp())) {
		 * info.setStatus(1);
		 * info.setCname(map.get(info.getIp()).getSocket().getInetAddress
		 * ().getHostName());
		 * 
		 * // 根据考试分配机器信息 SocketUser user = map.get(info.getIp()); if
		 * (returnMap.get(user.getExamId()) != null) { ArrayList<MachineInfo>
		 * list = returnMap.get(user.getExamId()); list.add(info);
		 * returnMap.put(user.getExamId(), list); } else {
		 * ArrayList<MachineInfo> list = new ArrayList<MachineInfo>();
		 * list.add(info); returnMap.put(user.getExamId(), list); } } }
		 */

		ListUtils.sort(list, true, "status", "field3");

		return list;
	}

	@Override
	public Result sendMsg(MsgBody msg) {

		String ip = msg.getClientIp();

		Map<String, SocketUser> socketUsers = serverSocketLine.getClients();
		Map<String, MachineInfo> infoMap = clientServiceImpl
				.getMachineInfoMap();
		try {
			if (socketUsers.get(ip) != null) {
				MachineInfo machineInfo = infoMap.get(ip);
				DeliverySocketMsgLog msgLog = new DeliverySocketMsgLog();
				
				msgLog.setMsg(msg.getMsg());
				msgLog.seteId(machineInfo.getField4());
				msgLog.seteNo(machineInfo.geteNo());
				msgLog.setsNo(machineInfo.getsNo());
				msgLog.setsName(machineInfo.getsName());

				String[] strs = msg.getMsg().split(",");
				if ("commit".equals(strs[0])) {
					msgLog.setMsgType(2);
				} else if ("delay".equals(strs[0])) {
					msgLog.setMsgType(1);
					msgLog.setDelayTime(new BigDecimal(strs[2]));
				}

				List<DeliverySocketMsgLog> list = deliverySocketMsgLogMapper
						.selectByParams(msgLog);
				if (list.size() > 0) {
					DeliverySocketMsgLog data = list.get(0);
					msgLog.setId(data.getId());
					deliverySocketMsgLogMapper.updateByPrimaryKey(msgLog);
				} else {
					msgLog.setId(Tool.getUUID());
					msgLog.setCreateTime(new Date());
					deliverySocketMsgLogMapper.insert(msgLog);
				}

				PrintWriter pw = socketUsers.get(ip).getPw();
				pw.println(msg.getMsg());
				pw.flush();

				return new Result(200, "信息发送成功");
			} else {
				return new Result(200, "机器处于离线状态");
			}
		} catch (Exception e) {
			e.printStackTrace();

			return new Result(8106, "报错了");
		}
	}

	@Override
	public Result selectAllDics(SysDictionary dic) {

		Map<String, String> params = new HashMap<String, String>();

		try {
			params.put("uniquecode", uniquecode);

			if (dic.getDicKey() != null && !"".equals(dic.getDicKey())) {
				params.put("dicKey", dic.getDicKey());
			}

			if (dic.getDicValue() != null && !"".equals(dic.getDicValue())) {
				params.put("dicValue", dic.getDicValue());
			}

			String resultStr = HttpClientUtil.doGet(centerUrl
					+ centerSysDicsUrl, params);

			GsonBuilder builder = new GsonBuilder();
			builder.registerTypeAdapter(Date.class,
					new JsonDeserializer<Date>() {
						@Override
						public Date deserialize(JsonElement json, Type typeOfT,
								JsonDeserializationContext context)
								throws JsonParseException {
							return new Date(json.getAsJsonPrimitive()
									.getAsLong());
						}
					});

			Result entity = builder.create().fromJson(resultStr, Result.class);

			return entity;
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(8106, "出错了");
		}

	}

	@Override
	public Result isRegiste(CenterMacSignin centerMacSignin,
			HttpServletRequest request) {
		if (StringUtils.isBlank(centerMacSignin.getMacAddress())) {

			String mac = getMac(request);
			if (StringUtils.isBlank(mac)) {
				return new Result(8001, "MAC地址不能为空");
			} else {
				centerMacSignin.setMacAddress(mac);
			}
		}

		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("macAddress", centerMacSignin.getMacAddress());
			params.put("uniqueCode", uniquecode);

			String resultStr = HttpClientUtil.doPost(
					centerUrl + centerValidate, params);

			if (null != resultStr) {
				Result result = new Gson().fromJson(resultStr, Result.class);

				return result;
			} else {

				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public DataEntity getOperationAuth(Integer id) {

		Map<String, String> params = new HashMap<String, String>();

		try {
			params.put("uniquecode", uniquecode);
			params.put("userId", id.toString());

			String resultStr = HttpClientUtil.doGet(centerUrl
					+ centerOperationAuthUrl, params);

			GsonBuilder builder = new GsonBuilder();
			builder.registerTypeAdapter(Date.class,
					new JsonDeserializer<Date>() {
						@Override
						public Date deserialize(JsonElement json, Type typeOfT,
								JsonDeserializationContext context)
								throws JsonParseException {
							return new Date(json.getAsJsonPrimitive()
									.getAsLong());
						}
					});

			DataEntity entity = builder.create().fromJson(resultStr,
					DataEntity.class);

			return entity;
		} catch (Exception e) {
			e.printStackTrace();
			return new DataEntity("8106", false, "出错了");
		}

	}

	@Override
	public DataEntity getDifficulty() {

		Map<String, String> params = new HashMap<String, String>();

		try {
			params.put("uniquecode", uniquecode);

			String resultStr = HttpClientUtil.doGet(centerUrl
					+ centerDifficultyUrl, params);

			GsonBuilder builder = new GsonBuilder();
			builder.registerTypeAdapter(Date.class,
					new JsonDeserializer<Date>() {
						@Override
						public Date deserialize(JsonElement json, Type typeOfT,
								JsonDeserializationContext context)
								throws JsonParseException {
							return new Date(json.getAsJsonPrimitive()
									.getAsLong());
						}
					});

			DataEntity entity = builder.create().fromJson(resultStr,
					DataEntity.class);

			return entity;
		} catch (Exception e) {
			e.printStackTrace();
			return new DataEntity("8106", false, "出错了");
		}
	}

	@Override
	public Result changePassword(Integer userid, String oldpassword,
			String newpassword) {

		Map<String, String> params = new HashMap<String, String>();

		try {
			params.put("uniquecode", uniquecode);

			params.put("userid", userid.toString());
			params.put("oldpassword", oldpassword);
			params.put("newpassword", newpassword);

			String resultStr = HttpClientUtil.doGet(centerUrl
					+ centerChangePwdUrl, params);

			GsonBuilder builder = new GsonBuilder();
			builder.registerTypeAdapter(Date.class,
					new JsonDeserializer<Date>() {
						@Override
						public Date deserialize(JsonElement json, Type typeOfT,
								JsonDeserializationContext context)
								throws JsonParseException {
							return new Date(json.getAsJsonPrimitive()
									.getAsLong());
						}
					});

			Result entity = builder.create().fromJson(resultStr, Result.class);

			if (entity.getCode() == 200) {
				DeliveryUser dUser = new DeliveryUser();
				dUser.setFree2(userid);
				List<DeliveryUser> users = deliveryUserMapper
						.selectByParams(dUser);

				if (users.size() > 0) {
					DeliveryUser updateUser = users.get(0);
					updateUser.setPassword(newpassword);
					deliveryUserMapper.updateByPrimaryKey(updateUser);
				}
			}

			return entity;
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(8106, "出错了");
		}
	}

	@Override
	public ResultForDeliverySysOrganization getOrganInfo() {

		Map<String, String> params = new HashMap<String, String>();

		try {
			Result testConn = systemService.TestConn();

			if (testConn.getCode() == 200) {
				params.put("uniquecode", uniquecode);

				String resultStr = HttpClientUtil.doGet(centerUrl
						+ centerSysOrganInfoUrl, params);

				GsonBuilder builder = new GsonBuilder();
				builder.registerTypeAdapter(Date.class,
						new JsonDeserializer<Date>() {
							@Override
							public Date deserialize(JsonElement json,
									Type typeOfT,
									JsonDeserializationContext context)
									throws JsonParseException {
								return new Date(json.getAsJsonPrimitive()
										.getAsLong());
							}
						});

				ResultForDeliverySysOrganization entity = builder.create()
						.fromJson(resultStr,
								ResultForDeliverySysOrganization.class);

				return entity;
			} else {
				DeliverySysOrganization sysOrgan = new DeliverySysOrganization();
				sysOrgan.setUniqueCode(uniquecode);

				List<DeliverySysOrganization> list = deliverySysOrganizationMapper
						.selectByParams(sysOrgan);

				if (list.size() > 0) {

					return new ResultForDeliverySysOrganization(list.get(0));
				} else {

					return new ResultForDeliverySysOrganization(8106,
							"没有获取到本地存储的学校信息");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ResultForDeliverySysOrganization(8106, "出错了");
		}
	}

	@Override
	public void checkUpgradeForExam() {
		Map<String, String> params = new HashMap<String, String>();

		try {
			params.put("uniquecode", uniquecode);

			String resultStr = HttpClientUtil.doGet(centerUrl + centerSysVersionInfo, params);

			GsonBuilder builder = new GsonBuilder();
			builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
				@Override
				public Date deserialize(JsonElement json, Type typeOfT,	JsonDeserializationContext context) throws JsonParseException {
					return new Date(json.getAsJsonPrimitive().getAsLong());
				}
			});

			ResultForDeliveryVersionUpgrade entity = builder.create().fromJson(resultStr, ResultForDeliveryVersionUpgrade.class);
			
			if ("200".equals(entity.getStatusCode())) {
				DeliveryVersionUpgrade newVersion = entity.getData();
				if (newVersion != null) {
					DeliveryVersionUpgrade version = deliveryVersionUpgradeMapper.selectByPrimaryKey(newVersion.getId());
					OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
					
					if (version != null) {
						if (!newVersion.getVersionNo().equals(version.getVersionNo())) {
							String filePath = clientPath + "/" + newVersion.getVersionNo();
							String key = newVersion.getFilePath();
							String allPath = filePath + "/" + key;
							File file = new File(allPath);
							if (!file.getParentFile().exists()) {
								file.getParentFile().mkdirs();
							}
							
							ossClient.getObject(new GetObjectRequest(bucket, key), file);
						}
						
						deliveryVersionUpgradeMapper.updateByPrimaryKey(newVersion);
					} else {
						// 删除旧版本
						List<DeliveryVersionUpgrade> his = deliveryVersionUpgradeMapper.selectAll();
						for (DeliveryVersionUpgrade deliveryVersionUpgrade : his) {
							deliveryVersionUpgradeMapper.deleteByPrimaryKey(deliveryVersionUpgrade.getId());
						}
						
						String filePath = clientPath + "/" + newVersion.getVersionNo();
						String key = newVersion.getFilePath();
						String allPath = filePath + "/" + key;
						File file = new File(allPath);
						if (!file.getParentFile().exists()) {
							file.getParentFile().mkdirs();
						}
						ossClient.getObject(new GetObjectRequest(bucket, key), file);
						
						deliveryVersionUpgradeMapper.insert(newVersion);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public DeliveryVersionUpgrade selectUpdateInfo() {
		
		List<DeliveryVersionUpgrade> list = deliveryVersionUpgradeMapper.selectAll();
		
		if (list.size() > 0) {

			return list.get(0);
		} else {
			
			return null;
		}
	}

	@Override
	public Result createUserByDirector(User user, Integer id) {

		Map<String, Object> params = new HashMap<String, Object>();
		
		try {
			params.put("uniquecode", uniquecode);
			
			if (user.getUsername() != null && !"".equals(user.getUsername())) {
				params.put("username", user.getUsername());
			}
			
			if (user.getRealname() != null && !"".equals(user.getRealname())) {
				params.put("realname", user.getRealname());
			}
			
			if (user.getEmail() != null && !"".equals(user.getEmail())) {
				params.put("email", user.getEmail());
			}
			
			if (user.getPhone() != null && !"".equals(user.getPhone())) {
				params.put("phone", user.getPhone());
			}
			
			String questionBankStr = HttpClientUtil.doPost(centerUrl + centerCreateUserUrl + "/" + id, params);
			
			GsonBuilder builder = new GsonBuilder();
			builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { 
		    	@Override   
		    	public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
		    		return new Date(json.getAsJsonPrimitive().getAsLong()); 
		    	}
		    });
			
			Result entity = builder.create().fromJson(questionBankStr, Result.class);
			
			return entity;
		} catch(Exception e) {
			e.printStackTrace();
			return new Result(8106, "出错了");
		}
	}

	@Override
	public Result editTeacher(User user) {

		Map<String, Object> params = new HashMap<String, Object>();
		
		try {
			params.put("uniquecode", uniquecode);
			
			if (user.getId() != null && !"".equals(user.getId())) {
				params.put("id", user.getId());
			}
			
			if (user.getUsername() != null && !"".equals(user.getUsername())) {
				params.put("username", user.getUsername());
			}
			
			if (user.getRealname() != null && !"".equals(user.getRealname())) {
				params.put("realname", user.getRealname());
			}
			
			if (user.getEmail() != null && !"".equals(user.getEmail())) {
				params.put("email", user.getEmail());
			}
			
			if (user.getPhone() != null && !"".equals(user.getPhone())) {
				params.put("phone", user.getPhone());
			}
			
			String questionBankStr = HttpClientUtil.doPost(centerUrl + centerEditUserUrl, params);
			
			GsonBuilder builder = new GsonBuilder();
			builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { 
		    	@Override   
		    	public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
		    		return new Date(json.getAsJsonPrimitive().getAsLong()); 
		    	}
		    });
			
			Result entity = builder.create().fromJson(questionBankStr, Result.class);
			
			return entity;
		} catch(Exception e) {
			e.printStackTrace();
			return new Result(8106, "出错了");
		}
	}

	@Override
	public DataEntity getTeacherList(User user, int page, int rows, Integer id) {

		Map<String, String> params = new HashMap<String, String>();
		
		try {
			params.put("uniquecode", uniquecode);
			
			if (user.getUsername() != null && !"".equals(user.getUsername())) {
				params.put("username", user.getUsername());
			}
			
			if (user.getRealname() != null && !"".equals(user.getRealname())) {
				params.put("realname", user.getRealname());
			}
			
			params.put("page", String.valueOf(page));
			params.put("rows", String.valueOf(rows));
			
			String questionBankStr = HttpClientUtil.doGet(centerUrl + centerListUserUrl + "/" + id, params);
			
			GsonBuilder builder = new GsonBuilder();
			builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { 
		    	@Override   
		    	public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
		    		return new Date(json.getAsJsonPrimitive().getAsLong()); 
		    	}
		    });
			
			DataEntity entity = builder.create().fromJson(questionBankStr, DataEntity.class);
			
			return entity;
		} catch(Exception e) {
			e.printStackTrace();
			return new DataEntity("8106", false, "出错了");
		}
	}

	@Override
	public Result deleteTeacher(Integer id, Integer userId) {

		Map<String, String> params = new HashMap<String, String>();
		
		try {
			params.put("uniquecode", uniquecode);
			params.put("id", id.toString());
			
			String questionBankStr = HttpClientUtil.doGet(centerUrl + centerDelUserUrl + "/" + userId, params);
			
			GsonBuilder builder = new GsonBuilder();
			builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { 
		    	@Override   
		    	public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
		    		return new Date(json.getAsJsonPrimitive().getAsLong()); 
		    	}
		    });
			
			Result entity = builder.create().fromJson(questionBankStr, Result.class);
			
			return entity;
		} catch(Exception e) {
			e.printStackTrace();
			return new Result(8106, "出错了");
		}
	}
	
	
}
